package org.ucas.kgraph.utils.common;


import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.usertype.ParameterizedType;
import org.hibernate.usertype.UserType;
import org.ucas.kgraph.dto.RelationDto;
import org.ucas.kgraph.entity.RelationType;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Properties;

public  class RelationTypeHandler implements UserType,ParameterizedType{


  public Object assemble(Serializable cached, Object owner)
          throws HibernateException {
    return cached;
  }

  public Object deepCopy(Object value) throws HibernateException {
    return value;
  }

  public Serializable disassemble(Object value) throws HibernateException {
    return (Serializable) value;
  }

  public boolean equals(Object x, Object y) throws HibernateException {
    if (x == y)
      return true;
    if (null == x || null == y)
      return false;
    return x.equals(y);
  }

  public int hashCode(Object x) throws HibernateException {
    return x.hashCode();
  }

  public boolean isMutable() {
    return false;
  }

  @Override
  public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor sessionImplementor,Object owner)
          throws HibernateException, SQLException {
    String s = rs.getString(names[0]);
    if (s != null) {
      return RelationType.valueOf(Integer.valueOf(s));
    }
    return null;
  }

  @Override
  public void nullSafeSet(PreparedStatement st, Object value, int index,SessionImplementor sessionImplementor)
          throws HibernateException, SQLException {
    if (null == value) {
      st.setNull(index, sqlTypes()[0]);
    } else {
      st.setString(index, ((RelationType) value).id.toString());
    }
  }

  public Object replace(Object original, Object target, Object owner)
          throws HibernateException {
    return original;
  }

  @SuppressWarnings("unchecked")
  public Class returnedClass() {
    return RelationType.class;
  }

  private static int[]    types    = new int[] { Types.TINYINT };

  public int[] sqlTypes() {
    return types;
  }

  @Override
  public void setParameterValues(Properties properties) {

  }
}